﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Security.Claims;
namespace DX.Security
{
  
    public class AdoDatabaseProvider : ISecurityProvider
    {
        private IDbConnection dbconnection;

        public AdoDatabaseProvider(IDbConnection dbconnection)
        {
            this.dbconnection = dbconnection;
        }



        // 从数据库加载策略（含异常处理）
        public IList<AbacPolicy> GetPolicies()
        {
            try
            {
                var policies = new List<AbacPolicy>();


                dbconnection.Open();
                var query = "SELECT * FROM AbacPolicies";
                using var cmd = dbconnection.CreateCommand();
                cmd.CommandText = query;
                cmd.Connection = dbconnection;
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        policies.Add(new AbacPolicy
                        {
                            Id = reader.GetInt32(0),
                            SubjectClaims = ParseClaims(reader.GetString(1)),
                            ResourceClaims = ParseClaims(reader.GetString(2)),
                            Action = reader.GetString(3),
                            IsAllowed = reader.GetBoolean(4)
                        });
                    }
                }

                return policies;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库加载策略失败: {ex.Message}");
                return new List<AbacPolicy>();
            }
        }
        private IList<Claim> ParseClaims(string attributeString)
        {
            var claims = new List<Claim>();
            if (string.IsNullOrEmpty(attributeString)) return claims;

            foreach (var attr in attributeString.Split(','))
            {
                var parts = attr.Split(':');
                if (parts.Length == 2)
                {
                    claims.Add(new Claim(parts[0], parts[1]));
                }
                else
                {
                    Console.WriteLine($"无效的属性格式: {attr}");
                }
            }
            return claims.AsReadOnly();
        }
    }


}